package com.meiyu.live.tv.utils;

import android.text.TextUtils;

import com.netease.nimlib.sdk.chatroom.model.ChatRoomMessage;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomNotificationAttachment;
import com.netease.nimlib.sdk.msg.constant.MsgTypeEnum;
import com.netease.nimlib.sdk.msg.constant.NotificationType;
import com.meiyu.live.comm.UserConfig;
import com.meiyu.live.popj.Gift;
import com.meiyu.live.popj.RoomDanmuMessage;
import com.meiyu.live.popj.RoomMessage;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by zbl on 2016/8/31.
 */
public class ChatRoomMessageParser {

    public static final int TYPE_ENTER_MESSAGE = 0;
    public static final int TYPE_EXIT = 1;
    public static final int TYPE_GIFT = 2;
    public static final int TYPE_ROOM_MESSAGE = 3;
    public static final int TYPE_DANMU_MESSAGE = 4;
    public static final int TYPE_FINISH_LIVE = 5;
    public static final int TYPE_ATMOSPHERE = 8;
    public static final int TYPE_SYS_DANMU_MESSAGE = 9;
    public static final int TYPE_GAME_DEAL = 10;
    public static final int TYPE_GAME_BET = 11;

    public interface ChatRoomMessageParseListener {
        void onGift(Gift gift);

        void onMessage(RoomMessage roomMessage);

        void onEnterMessage(RoomMessage roomMessage, boolean isTargetMe);

        void onExitMessage(RoomMessage roomMessage);

        void onDanmuMessage(RoomDanmuMessage roomDanmuMessage);

        void onFinishLive();

        void onSetManager(RoomMessage roomMessage, boolean isManager, boolean isTargetMe);

        void onSetMute(RoomMessage roomMessage, boolean isMute, boolean isTargetMe);

        void onLightOn(RoomMessage roomMessage);

        void onGameDeal();

        void onGameBet();
    }

    private ChatRoomMessageParseListener listener;

    public ChatRoomMessageParser(ChatRoomMessageParseListener listener) {
        this.listener = listener;
    }

    public void parse(ChatRoomMessage message) {

        final Map<String, Object> dataMap = message.getRemoteExtension();
        if (dataMap != null) {
            try {
                Integer type = (Integer) dataMap.get("type");
                if (type != null) {
                    switch (type) {
                        case TYPE_EXIT: {
//                            final RoomMessage roomMessage = new RoomMessage();
//                            roomMessage.setName((String) dataMap.get("name"));
//                            roomMessage.setAvatar((String) dataMap.get("avatar"));
//                            roomMessage.setUser_id(optString(dataMap, "user_id"));
//                            roomMessage.setNet_ease_id((String) dataMap.get("net_ease_id"));
//                            Integer level = (Integer) dataMap.get("level");
//                            if (level != null) {
//                                roomMessage.setLevel(level);
//                            }
//                            roomMessage.setContent(message.getContent());
//                            roomMessage.setType(1);
//                            roomMessage.setOperatorNeteaseId(roomMessage.getNet_ease_id());
//                            listener.onExitMessage(roomMessage);
                        }
                        break;
                        case TYPE_GIFT: {
                            final Gift gift = new Gift();
                            gift.name = (String) dataMap.get("name");
                            gift.net_ease_id = (String) dataMap.get("net_ease_id");
                            gift.user_id = optString(dataMap, "user_id");
                            gift.icon = (String) dataMap.get("icon");
                            gift.level = (int) dataMap.get("level");
                            gift.gift_type = (String) dataMap.get("gift_type");
                            gift.gift_name = (String) dataMap.get("gift_name");
                            gift.gift_icon = (String) dataMap.get("gift_icon");
                            gift.gift_count = (int) dataMap.get("gift_count");
                            gift.gift_scale = (int) dataMap.get("gift_scale");
                            gift.gift_price = (int) dataMap.get("gift_price");
                            gift.is_dynamic = ((int) dataMap.get("gift_is_dynamic")) != 0;
                            gift.animation = (String) dataMap.get("gift_animation");
                            listener.onGift(gift);
                        }
                        break;
                        case TYPE_ROOM_MESSAGE: {
                            final RoomMessage roomMessage = new RoomMessage();
                            roomMessage.setName((String) dataMap.get("name"));
                            roomMessage.setAvatar((String) dataMap.get("avatar"));
                            roomMessage.setUser_id(optString(dataMap, "user_id"));
                            roomMessage.setNet_ease_id((String) dataMap.get("net_ease_id"));
                            Integer level = (Integer) dataMap.get("level");
                            if (level != null) {
                                roomMessage.setLevel(level);
                            }
                            roomMessage.setContent(message.getContent());
                            listener.onMessage(roomMessage);
                        }
                        break;
                        case TYPE_DANMU_MESSAGE: {
                            final RoomDanmuMessage roomDanmuMessage = new RoomDanmuMessage();
                            roomDanmuMessage.setType(TYPE_DANMU_MESSAGE);
                            roomDanmuMessage.setName((String) dataMap.get("name"));
                            roomDanmuMessage.setAvatar((String) dataMap.get("avatar"));
                            roomDanmuMessage.setUser_id(optString(dataMap, "user_id"));
                            roomDanmuMessage.setNet_ease_id((String) dataMap.get("net_ease_id"));
                            roomDanmuMessage.setContent(message.getContent());
                            listener.onDanmuMessage(roomDanmuMessage);
                        }
                        break;
                        case TYPE_SYS_DANMU_MESSAGE: {
                            final RoomDanmuMessage roomDanmuMessage = new RoomDanmuMessage();
                            roomDanmuMessage.setType(TYPE_SYS_DANMU_MESSAGE);
                            roomDanmuMessage.setName((String) dataMap.get("name"));
                            roomDanmuMessage.setAvatar((String) dataMap.get("avatar"));
                            roomDanmuMessage.setUser_id(optString(dataMap, "user_id"));
                            roomDanmuMessage.setNet_ease_id((String) dataMap.get("net_ease_id"));
                            roomDanmuMessage.setContent(message.getContent());
                            roomDanmuMessage.setValue((int) dataMap.get("value"));
                            listener.onDanmuMessage(roomDanmuMessage);
                        }
                        break;
                        case TYPE_FINISH_LIVE: {
                            listener.onFinishLive();
                        }
                        break;
                        case TYPE_ENTER_MESSAGE: {
                            final RoomMessage roomMessage = new RoomMessage();
                            roomMessage.setName((String) dataMap.get("name"));
                            roomMessage.setAvatar((String) dataMap.get("avatar"));
                            roomMessage.setUser_id(optString(dataMap, "user_id"));
                            roomMessage.setNet_ease_id((String) dataMap.get("net_ease_id"));
                            Integer level = (Integer) dataMap.get("level");
                            if (level != null) {
                                roomMessage.setLevel(level);
                            }
                            roomMessage.setContent("来了,欢迎~");
                            roomMessage.setType(1);
                            roomMessage.setOperatorNeteaseId(roomMessage.getNet_ease_id());
                            listener.onEnterMessage(roomMessage, false);
                        }
                        break;
                        case TYPE_ATMOSPHERE: {
                            final RoomMessage roomMessage = new RoomMessage();
                            roomMessage.setType(1);
                            roomMessage.setName((String) dataMap.get("name"));
                            roomMessage.setAvatar((String) dataMap.get("avatar"));
                            roomMessage.setUser_id(optString(dataMap, "user_id"));
                            roomMessage.setNet_ease_id((String) dataMap.get("net_ease_id"));
                            Integer level = (Integer) dataMap.get("level");
                            if (level != null) {
                                roomMessage.setLevel(level);
                            }
                            roomMessage.setContent("点亮了");
                            listener.onLightOn(roomMessage);
                        }
                        break;
                        case TYPE_GAME_DEAL: {
                            listener.onGameDeal();
                        }
                        break;
                        case TYPE_GAME_BET: {
                            listener.onGameDeal();
                        }
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            if (message.getMsgType() == MsgTypeEnum.notification) {
                if (message.getAttachment() instanceof ChatRoomNotificationAttachment) {
                    ChatRoomNotificationAttachment attachment = (ChatRoomNotificationAttachment) message.getAttachment();
                    String targetNick = null;
                    String targetNeteaseId = null;
                    boolean isTargetMe = false;
                    if (attachment.getTargetNicks().size() > 0) {
                        targetNick = attachment.getTargetNicks().get(0);
                        targetNeteaseId = attachment.getTargets().get(0);
                        isTargetMe = TextUtils.equals(UserConfig.getInstance().getNet_ease(), attachment.getTargets().get(0));
                    }
                    String operatorNeteaseId = attachment.getOperator();
                    String operatorNick = attachment.getOperatorNick();

                    RoomMessage roomMessage = new RoomMessage();
                    roomMessage.setType(2);
                    roomMessage.setOperatorNeteaseId(operatorNeteaseId);
                    roomMessage.setTargetNeteaseId(targetNeteaseId);

                    if (NotificationType.ChatRoomManagerAdd == attachment.getType()) {
                        if (targetNick != null) {
                            roomMessage.setContent("用户 " + targetNick + " 被房主设为场控");
                        }
                        listener.onSetManager(roomMessage, true, isTargetMe);
                    } else if (NotificationType.ChatRoomManagerRemove == attachment.getType()) {
                        if (targetNick != null) {
                            roomMessage.setContent("用户 " + targetNick + " 被房主取消场控权限");
                        }
                        listener.onSetManager(roomMessage, false, isTargetMe);
                    } else if (NotificationType.ChatRoomMemberMuteAdd == attachment.getType()) {
                        if (targetNick != null && operatorNick != null) {
                            roomMessage.setContent("用户 " + targetNick + " 被场控 " + operatorNick + " 禁止发言");
                        }
                        listener.onSetMute(roomMessage, true, isTargetMe);
                    } else if (NotificationType.ChatRoomMemberMuteRemove == attachment.getType()) {
                        if (targetNick != null && operatorNick != null) {
                            roomMessage.setContent("用户 " + targetNick + " 被场控 " + operatorNick + " 解除禁言");
                        }
                        listener.onSetMute(roomMessage, false, isTargetMe);
                    } else if (NotificationType.ChatRoomMemberIn == attachment.getType()) {
                        roomMessage.setContent("来了,欢迎~");
                        roomMessage.setType(1);
                        final Map<String, Object> notifyMap = attachment.getExtension();
                        if (notifyMap != null) {
                            if (notifyMap.containsKey("ext")) {
                                handleRobotMember(roomMessage, targetNeteaseId, (String) notifyMap.get("ext"));
                            } else {
                                try {
                                    roomMessage.setName((String) notifyMap.get("nick"));
                                    roomMessage.setAvatar((String) notifyMap.get("icon"));
                                    roomMessage.setNet_ease_id((String) notifyMap.get("net_ease_id"));
                                    Integer level = (Integer) notifyMap.get("level");
                                    if (level != null) {
                                        roomMessage.setLevel(level);
                                    }
                                    roomMessage.setUser_id((String) notifyMap.get("user_id"));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        if (!TextUtils.isEmpty(roomMessage.getName())) {
                            listener.onEnterMessage(roomMessage, isTargetMe);
                        }
                    } else if (NotificationType.ChatRoomMemberExit == attachment.getType()) {
                        roomMessage.setType(1);
                        listener.onExitMessage(roomMessage);
                    }
                }
            }
        }
    }

    private HashMap<String, JSONObject> robotMap = new HashMap<>();

    private void handleRobotMember(RoomMessage roomMessage, String netease_id, String ext) {//更新机器人map数据
        JSONObject data = robotMap.get(netease_id);
        if (data == null) {
            try {
                JSONArray jsonArray = new JSONArray(ext);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject object = jsonArray.getJSONObject(i);
                    String netEaseId = object.optString("net_ease_id");
                    if (!TextUtils.isEmpty(netEaseId)) {
                        robotMap.put(netEaseId, object);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            data = robotMap.get(netease_id);
        }
        if (data != null) {
            try {
                roomMessage.setName((String) data.opt("nick"));
                roomMessage.setAvatar((String) data.opt("icon"));
                roomMessage.setNet_ease_id((String) data.opt("net_ease_id"));
                Object level = data.opt("level");
                if (level != null) {
                    if (level instanceof Integer) {
                        roomMessage.setLevel((Integer) level);
                    } else if (level instanceof String) {
                        roomMessage.setLevel(Integer.parseInt((String) level));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private String optString(Map<String, Object> dataMap, String key) {
        String value = null;
        if (dataMap != null && key != null) {
            Object object = dataMap.get(key);
            if (object != null) {
                if (object instanceof String) {
                    value = (String) object;
                } else if (object instanceof Integer) {
                    value = ((int) object) + "";
                }
            }
        }
        return value;
    }
}
